#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <pthread.h>
#include "uart_tool.h"

int fd;

void *serialRead(void *argv){
	char buffer[33];
	int n_read;
	while(1){
		if((n_read = mySerialReadString (fd, buffer)) < 0){
			perror("read");
			exit(-1);
		}
		else if(n_read > 0){
			buffer[n_read] = '\0';
			printf("GET->%s\n",buffer);
		}
	}
	return NULL;
}

void *serialWrite(void *argv){
	char buffer[32];
	printf("Enter message to send: ");
	fflush(stdout);//确保立即显示
	while(fgets(buffer,sizeof(buffer),stdin)!=NULL){
		buffer[strcspn(buffer,"\r\n")] = 0;
		mySerialWriteString(fd, buffer);
		printf("Enter message to send: ");
		fflush(stdout);
	}
	return NULL;
}

int main(int argc,char **argv){
	char deviceName[32] = {'\0'};
	pthread_t pid_read;
	pthread_t pid_write;

	if(argc < 2){
		perror("/dev/ttyS?");
		exit(-1);
	}

	strcpy(deviceName,argv[1]);

	if((fd =  mySerialOpen(deviceName, 115200)) < 0){
		perror("serialOpen");
		exit(-1);
	}

	pthread_create(&pid_read, NULL, serialRead, NULL);
	pthread_create(&pid_write, NULL, serialWrite, NULL);

	pthread_join(pid_read,NULL);
	pthread_join(pid_write,NULL);

	return 0;
}
